package com.qf.controller;

import com.qf.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * author:z
 * time:2022/1/7 10:58
 * description:
 */
@RestController
@RequestMapping("/auth")
public class LoginController {

    @Value("${custom.username}")
    private String uname;

    @Value("${custom.password}")
    private String pwd;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/login")
    public String login(String username,String password){
        //判断用户名和密码是否相等
        if(username.equals(username)&&pwd.equals(password)){
            //生成jwt
            String jti = UUID.randomUUID().toString();
            String token = JwtUtil.createJWT(jti, username, null);
            //将jwt放到用户浏览器cookie中
            Cookie cookie=new Cookie("token",token);

            //存入redis中
//            redisTemplate.boundValueOps(jti).set(token);

            redisTemplate.boundHashOps("jti").put(jti,token);

            //路径
            cookie.setPath("/");
            //cookie生存校验，浏览器关闭之后会消失
            cookie.setMaxAge(-1);
            //关闭安全校验
            cookie.setHttpOnly(false);
            //把cookie保存响应给客户
            response.addCookie(cookie);
            return "登录成功！";

        }
        return "用户名或者密码错误!";
//        //判断用户名和密码是否相同
//        if(uname.equals(username)&&pwd.equals(password)) {
//            String jti = UUID.randomUUID().toString();
//            //生成jwt
//            String jwt = JwtUtil.createJWT(jti, username, null);
//            //将jwt放到cookie中
//            Cookie cookie=new Cookie("jwt",jwt);
//            //存入到redis中将jwt
//            redisTemplate.boundHashOps("jti").put(jti,jwt);
//            //路径
//            cookie.setPath("/");
//            //cookie生存时间，浏览器关闭后消失
//            cookie.setMaxAge(-1);
//            //关闭安全校验
//            cookie.setHttpOnly(false);
//            //把cookie保存响应给客户端
//            response.addCookie(cookie);
//        }
    }
}
